
#ifndef CLIENT_H
#define CLIENT_H

#include <iostream>
#include <string>
#include <cstring>
#include <stdint.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "log.hpp"

using namespace Logspace;

enum
{
    Socket_Err,
    Ip_Err,
};

class Client
{
public:
    Client(const std::string &ip, uint16_t port)
        : ip_(ip), port_(port) , sockfd_(-1)
    {
        memset(&server_ , 0 , sizeof(server_));
    }
    
    void Init()
    {
        sockfd_ = socket(AF_INET, SOCK_DGRAM, 0);
        if (sockfd_ < 0)
        {
            Log(Fatal) << "socket failed";
            exit(Socket_Err);
        }
        server_.sin_family = AF_INET;
        server_.sin_port = htons(port_);
        if (inet_aton(ip_.c_str(), &(server_.sin_addr)) == 0)
        {
            Log(Error) << "invalid IP address: " << ip_ ;
            close(sockfd_); // 先关闭已创建的socket
            exit(Ip_Err);        // 或其他错误码
        }
    }

    void Send(std::string message)
    {
        // 进行发送消息
        int n = sendto(sockfd_, message.c_str(), message.size(), 0, (sockaddr *)&server_, sizeof(server_));
    }

    std::string Recv()
    {
        char buffer[1024];
        struct sockaddr_in temp;
        socklen_t len = sizeof(temp);
        int n = recvfrom(sockfd_, buffer, sizeof(buffer) - 1, 0, (sockaddr *)&temp, &len);
        if (n > 0)
            buffer[n] = 0;

        return buffer;
    }


private:
    int sockfd_;    
    std::string ip_;
    struct sockaddr_in server_;
    uint16_t port_;
};

#endif
